<template>
  <div id="contianer">
    <el-row :gutter="10">
      <el-col :span="5">
        <el-scrollbar :style="scrollHeight">
          <el-card shadow="never" :body-style="contentViewHeight">
            <div class="title">知识数据目录</div>
            <el-tree
              show-checkbox
              :data="deptOptions"
              :props="defaultProps"
              :expand-on-click-node="false"
              ref="tree"
              node-key="id"
              default-expand-all
              :default-checked-keys="checkedArr"
              highlight-current
              @check-change="handleCheckChange"
              @node-click="handleNodeClick"
            />
          </el-card>
        </el-scrollbar>
      </el-col>
      <!--用户数据-->
      <el-col :span="19">
        <el-scrollbar :style="scrollHeight">
          <el-card shadow="never" :body-style="contentViewHeight">
            <el-form
              :model="queryParams"
              ref="queryForm"
              size="small"
              :inline="true"
              label-width="68px"
            >
              <el-form-item label="知识名称" prop="fileName">
                <el-input
                  v-model="queryParams.fileName"
                  placeholder="请输入知识名称"
                  clearable
                  style="width: 240px"
                />
              </el-form-item>
              <el-form-item>
                <el-button
                  type="primary"
                  icon="el-icon-search"
                  size="small"
                  @click="handleQuery"
                  >搜索</el-button
                >
                <el-button
                  icon="el-icon-refresh"
                  size="small"
                  @click="resetQuery"
                  >重置</el-button
                >
              </el-form-item>
            </el-form>
            <el-table
              v-if="userList"
              v-loading="loading"
              :data="userList"
              :max-height="tableClientHeight"
              ref="multipleTable"
              border
              @select="tableSelect"
              @selection-change="handleSelectionChange"
            >
              <el-table-column type="selection" width="55"> </el-table-column>
              <el-table-column
                label="知识名称"
                prop="knowledgeName"
                min-width="15%"
              />
              <el-table-column
                label="源文件名称"
                align="center"
                prop="fileName"
                :show-overflow-tooltip="true"
                min-width="15%"
              />
              <el-table-column
                label="文件版次"
                align="center"
                prop="fileVersion"
                :show-overflow-tooltip="true"
                min-width="15%"
              />
              <el-table-column
                label="文件编号"
                align="center"
                prop="fileCode"
                :show-overflow-tooltip="true"
                min-width="15%"
              />
              <el-table-column
                label="文件类型"
                align="center"
                prop="fileTypeName"
                :show-overflow-tooltip="true"
                min-width="15%"
              />
              <el-table-column
                label="上传人员"
                align="center"
                prop="uploadUser"
                min-width="15%"
              />
              <el-table-column
                label="作者姓名"
                align="center"
                prop="author"
                :show-overflow-tooltip="true"
                min-width="15%"
              />
              <el-table-column
                label="数据来源"
                align="center"
                prop="sourceName"
                min-width="15%"
              />
              <el-table-column
                label="上传日期"
                align="center"
                prop="uploadTime"
                :show-overflow-tooltip="true"
                min-width="15%"
              />
              <el-table-column
                label="文件格式"
                align="center"
                prop="fileFormat"
                min-width="15%"
              />
              <el-table-column
                label="解析状态"
                align="center"
                prop="analyseStatusName"
                :show-overflow-tooltip="true"
                min-width="15%"
              />
              <el-table-column
                label="发布状态"
                align="center"
                prop="dataStatusName"
                min-width="15%"
              />

              <el-table-column
                label="操作"
                align="center"
                min-width="20%"
                class-name="small-padding fixed-width"
              >
                <template slot-scope="scope">
                  <el-link
                    type="primary"
                    style="display: inline-block; margin-left: 10px"
                    @click="edit(scope.row)"
                    >编辑</el-link
                  >
                </template>
              </el-table-column>
            </el-table>

            <el-pagination
              v-if="userList"
              @size-change="sizeChangeHandle"
              @current-change="currentChangeHandle"
              :current-page="pageNo"
              :page-sizes="[10, 20, 50, 100]"
              :page-size="pageSize"
              :total="total"
              style="text-align: right; margin-top: 10px"
              layout="total, sizes, prev, pager, next, jumper"
            >
            </el-pagination>
            <div
              style="
                width: 100%;
                margin: 0px auto;
                display: flex;
                justify-content: center;
                position: absolute;
                bottom: 20px;
              "
            >
              <el-button type="primary" @click="submitFn">保存</el-button>
            </div>
          </el-card>
        </el-scrollbar>
      </el-col>
    </el-row>
  </div>
</template>
<script>
export default {
  data() {
    return {
      searchForm: {},
      loading: true,
      total: 0,
      pageNo: 1,
      pageSize: 10,
      userList: null,
      defaultProps: {
        children: "children",
        label: "label",
      },
      userId: null,
      isDefault: true,
      queryParams: {
        fileName: "",
        fileType: null,
        profession: null,
      },
      treeListParams: {
        fileName: "",
        fileType: "",
        pageSize: -1,
        profession: "",
        userId: "",
      },
      deptOptions: [],
      multipleSelection: [],
      checkedArr: [32],
      selectionStatus: "",
      selectListArr: [],
    };
  },
  mounted() {
    // console.log(this.$route.query.userIds.split(',').length,this.$route.query.userIds)
    if(this.$route.query.userIds && this.$route.query.userIds.split(',').length == 1){
      this.userId = this.$route.query.userIds;
      this.isDefault = false;
    }
    
    this.getList();
    this.getDeptTree();
  },
  computed: {
    contentViewHeight() {
      const height = document.documentElement["clientHeight"] - 120;
      return { minHeight: height + "px" };
    },
    scrollHeight() {
      const height = document.documentElement["clientHeight"] - 110;
      return { height: height + "px" };
    },
    tableClientHeight() {
      let tableClientHeight =
        document.documentElement.clientHeight || document.body.clientHeight;
      tableClientHeight = tableClientHeight - 300;
      return tableClientHeight;
    },
  },
  methods: {
    getList() {
      this.loading = true;
      this.$http({
        url: "/outsidePermission/list",
        method: "get",
        params: {
          ...this.queryParams,
          pageSize: this.pageSize,
          pageNumber: this.pageNo,
          isDefault: this.isDefault,
          userId: this.userId,
          // professionList:[
          //   {
          //     major:1,
          //     fileType:[31]
          //   },{
          //     major:2
          //   }
          // ]
        },
      }).then(({ data }) => {
        this.userList = data.data.data;
        this.total = data.data.totalSize;
        // 这里需要处理默认选中的table列表
        // 设置默认选中的行

        const defaultSelected = this.userList.filter((item) => item.selected);

        defaultSelected.forEach((item) => {
          console.log("看看选中的数据", item);
          this.$nextTick(() => {
            this.$refs.multipleTable.toggleRowSelection(item, true);
          });
        });
        this.treerelationTable(
          this.queryParams.profession || this.queryParams.fileType
        );

        this.loading = false;
      });
    },
    // 保存
    submitFn() {
      const checkedNodes = this.$refs.tree.getCheckedNodes();
      let paramsList = {
        treeList: [],
        fileList: [],
        userIds:this.$route.query.userIds ? this.$route.query.userIds.split(',') :[]
      };
      console.log("用来凭拼接数据", this.selectListArr, checkedNodes);

      checkedNodes.map((item) => {
        if (item.level == 1) {
          paramsList.treeList.push({
            profession: item.value,
            allSelect: true,
            fileType: [],
          });
        }
          if (item.level == 2) {
            const result = paramsList.treeList.find(
              (H) => H.profession == item.parentId
            );
            console.log("找到对应数据",result)
            if (result) {
              result.fileType.push({
                id: item.value,
                allSelect: true,
              });
            } else {
              paramsList.treeList.push({
                profession: item.parentId,
                allSelect: false,
                fileType: [
                  {
                    id: item.value,
                    allSelect: true,
                  },
                ],
              });
            }
          }
      });
      this.selectListArr.map((item) => {
        paramsList.fileList.push({
          id: item.id,
          profession: item.profession,
          fileType: item.fileType,
          operate: item.selected == true ? 1 : item.selected == false ? 0 : item.selected,
        });
      });

      console.log("整合后的数据", paramsList);

      // return;
      this.$http({
        url: this.isDefault ? "/outsidePermission/editDefault" : "/outsidePermission/editUser",
        method: "post",
        data: {
          ...paramsList
        },
      }).then(({ data }) => {
        this.$message.success("权限配置成功")
        this.$tab.closePage();
        // this.$router.push('/system/user')
      });
    },
    getDeptTree() {
      this.$http({
        url: "/outsidePermission/treeList",
        method: "GET",
        params: {
          ...this.treeListParams,
          isDefault: this.isDefault,
          userId: this.userId,
        },
      }).then(({ data }) => {
        this.deptOptions = data.data;
        // 整理选中逻辑
        // 这里需要处理数据
        // checkedArr
        this.getCheckedKeys(this.deptOptions).map((val) => {
          this.$nextTick(() => {
            this.$refs.tree.setChecked(val, true, false);
          });
        });
        // this.getList();
      });
    },
    getCheckedKeys(data) {
      let keys = [];
      data.forEach((item) => {
        if (item.selected) {
          keys.push(item.id);
        }
        if (item.children) {
          keys = keys.concat(this.getCheckedKeys(item.children));
        }
      });
      return keys;
    },
    // fileListFn(){
    //   this.$http({
    //     url: "/outsidePermission/list",
    //     method: "GET",
    //     params: {},
    //   }).then(({ data }) => {
    //     // this.deptOptions = data.data;
    //     this.userList = data.data;
    //   });
    // },
    /** 搜索按钮操作 */
    handleQuery() {
      this.pageNo = 1;
      this.getList();
    },
    resetQuery() {
      this.queryParams.fileName = "";
      this.queryParams.fileType = "";
      this.queryParams.profession = "";
      this.pageNo = 1;
      this.$refs.tree.setCurrentKey(null);
      this.getList();
    },
    // 选中或取消
    tableSelect(rows, row) {
      console.log(rows, row);
      // 这里维护数据 手动push数据并且去重
      let selected = rows.length && rows.indexOf(row) !== -1;
      console.log(selected); // true就是选中，0或者false是取消选中

      // 这里选中就是true 否则 false
      row.selected = selected;

      const existingIndex = this.selectListArr.findIndex(
        (item) => item.id === row.id
      );
      if (existingIndex !== -1) {
        // 如果存在相同的 id，删除旧的数据
        this.selectListArr.splice(existingIndex, 1);
      }
      // 添加新数据
      this.selectListArr.push(row);

      console.log("看看最终整合的数据", this.selectListArr);
    },
    // 批量勾选/全选/反选
    handleSelectionChange(selectedRows) {
      const selectedIds = selectedRows.map(row => row.id);
      this.userList.forEach(item => {
        const isSelected = selectedIds.includes(item.id);
        if (item.selected !== isSelected) {
          this.recordSelectionChange(item, isSelected);
        }
      });
    },
    // 记录变化项到 selectListArr
    recordSelectionChange(row, selected) {
      row.selected = selected;
      const existingIndex = this.selectListArr.findIndex(item => item.id === row.id);
      if (existingIndex !== -1) {
        this.selectListArr.splice(existingIndex, 1);
      }
      this.selectListArr.push({...row});
    },
    // handleSelectionChange(row) {
    //   const tree = this.$refs.tree;
    //   this.multipleSelection = row;
    //   console.log("table已选择", this.multipleSelection, row);

    //   const totalRows = this.userList.length; // 总行数
    //   const selectedCount = row.length; // 已选行数

    //   if (selectedCount === 0) {
    //     this.selectionStatus = "未选";
    //   } else if (selectedCount === totalRows) {
    //     this.selectionStatus = "全选";
    //     // 设置目录节点为半选
    //     // tree.setCheckedKeys([id]); // 先设置为选中，确保状态同步
    //     // tree.setHalfCheckedKeys([row.id]); // 设置为半选状态
    //   } else {
    //     this.selectionStatus = "半选";
    //   }
    //   console.log(this.selectionStatus);
    // },
    // 每页数
    sizeChangeHandle(val) {
      this.pageSize = val;
      this.pageNo = 1;
      this.getList();
    },
    // 当前页
    currentChangeHandle(val) {
      this.pageNo = val;
      this.getList();
    },
    // tree点击事件
    handleNodeClick(data, node, item) {
      console.log(data, node, item, "tree点击事件");
      if (node.level === 2) {
        this.queryParams.profession = node.parent.data.value;
        this.queryParams.fileType = data.value;
        this.getList();
      } else if (node.level === 1) {
        this.queryParams.profession = data.value;
        this.queryParams.fileType = null;
        this.getList();
      }
      // this.treerelationTable(data)
    },
    // 选中框出发事件
    handleCheckChange(data, tag, tree) {
      const checkedNodes = this.$refs.tree.getCheckedNodes();
      console.log("勾选的节点数据", data, tag, tree, this.userList); // 打印被勾选的节点数据
      // 这里需要处理一级还是二级目录

      return;
      if (tag) {
        console.log("ffff");
        // 这里是选中操作
        // 判断当前左侧选中中存在右侧父级
        if (
          this.userList != null &&
          [this.userList[0].fileType, this.userList[0].profession].includes(
            data.value
          )
        ) {
          this.userList.forEach((item) => {
            this.$nextTick(() => {
              if (item.profession == data.parentId) {

              // 记录变化前的状态
              const origin = this.userList.find(u => u.id === item.id);
              const oldSelected = origin ? origin.selected : undefined;
              item.selected = true;
              this.$refs.multipleTable.toggleRowSelection(item, true);

              // 只记录变化的数据
              const existIdx = this.selectListArr.findIndex(i => i.id === item.id);
              if (oldSelected !== true) {
                if (existIdx !== -1) this.selectListArr.splice(existIdx, 1);
                this.selectListArr.push({...item});
                this.tableSelect(this.selectListArr, item);
              }
              //   this.$refs.multipleTable.toggleRowSelection(item, true);
                this.$forceUpdate();
            }
            });
          });
        }
      } else {
        console.log("取消选中");
        if (
          this.userList != null &&
          [this.userList[0].fileType, this.userList[0].profession].includes(
            data.value
          )
        ) {
          this.userList.forEach((item) => {
            this.$nextTick(() => {
                          if (item.profession == data.parentId) {

              const origin = this.userList.find(u => u.id === item.id);
              const oldSelected = origin ? origin.selected : undefined;
              item.selected = false;
              this.$refs.multipleTable.toggleRowSelection(item, false);

              // 只记录变化的数据
              const existIdx = this.selectListArr.findIndex(i => i.id === item.id);
              if (oldSelected !== false) {
                if (existIdx !== -1) this.selectListArr.splice(existIdx, 1);
                this.selectListArr.push({...item});
                this.tableSelect(this.selectListArr, item);
              }
              //   this.$refs.multipleTable.toggleRowSelection(item, true);
                this.$forceUpdate();
            }
            });
          });
        }
      }
      return;
      defaultSelected.forEach((item) => {
        console.log("看看选中的数据", item);
        this.$nextTick(() => {
          this.$refs.multipleTable.toggleRowSelection(item, true);
        });
      });
    },
    // 点击时候需要从左侧选中的树 关联右侧列表
    treerelationTable(key) {
      let that = this;
      const checkedNodes = this.$refs.tree.getCheckedNodes();

      const result = checkedNodes.find((item) => item.value == key);
      console.log("已选中的数据", checkedNodes, result, this.userList);
      if (result && that.userList != null) {
        // if(this.userList != null && [this.userList[0].fileType, this.userList[0].profession].includes(result.value)) {
        that.userList.forEach((item) => {
          that.$nextTick(() => {
            that.$refs.multipleTable.toggleRowSelection(item, true);
          });
        });
        // }
      }
    },
    edit(row) {
      this.$router.push({
        path: "/knowledgeLabels/details",
        query: {
          row,
        },
      });
    },
  },
};
</script>
<style lang="scss" scoped>
#contianer {
  //   width: 98%;
  //   min-height: 96%;
  //   background: white;
  border-radius: 10px;
  padding: 10px 20px 0;
  //   margin: 20px;

  .tree_menu {
    position: absolute;
    width: 18%;
    border-right: 1px solid rgb(117, 97, 97);
    height: 100%;

    h2 {
      font-size: 20px;
      font-weight: 550;
    }
  }
  .table {
    width: 78%;
    float: right;
    padding: 20px 20px 0 0;
  }

  .screen_model {
    margin-bottom: 20px;
  }
}
</style>
